package com.example.weixinapireptile.common.exceptions;

import com.example.weixinapireptile.common.result.Result;
import com.example.weixinapireptile.common.result.ResultStatus;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 业务异常
 */
@Getter
@Slf4j
@RestControllerAdvice
public class BizException extends RuntimeException {
    private static final long serialVersionUID = -7285211528095468156L;

    private ResultStatus resultStatus;

    private BizException() {
    }

    public BizException(String message) {
        super(message);
    }

    public BizException(ResultStatus resultStatus) {
        super(resultStatus.getMessage());
        this.resultStatus = resultStatus;
    }

    public BizException(Throwable cause) {
        super(cause);
    }

    public BizException(String errorMessage, Throwable cause) {
        super(errorMessage, cause);
    }

    public BizException(String errorMessage, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(errorMessage, cause, enableSuppression, writableStackTrace);
    }

    public static void throwe(String errorMessage) {
        throw new BizException(errorMessage);
    }

    public static void throwe(ResultStatus resultStatus) {
        throw new BizException(resultStatus);
    }

    /**
     * 将业务层抛出的异常信息捕获到，然后交给全局异常处理器去处理，给前端提供错误信息
     * @param exception
     * @return
     */
    @ExceptionHandler(BizException.class)
    public Result<String> exceptionCategoryDelete(BizException exception){
        log.error(exception.getMessage());//在控制台打印错误信息
        return Result.failed(exception.getMessage());

    }
}
